package com.glela.controller;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glela.api.pay.util.PaymentUtil;
import com.glela.api.pay.wechat.component.WeChat;
import com.glela.api.pay.yeepay.component.YeePay;
import com.glela.api.pay.yeepay.model.YeePayBaseRequest;
import com.glela.cache.redis.RedisKeys;
import com.glela.cache.redis.RedisUtil;
import com.glela.common.constant.BaseConstants;
import com.glela.common.constant.BaseRestrictionsEnum;
import com.glela.common.constant.CommonConstants;
import com.glela.common.constant.PayTypeEnum;
import com.glela.common.constant.StatusEnum;
import com.glela.common.exception.PlatformException;
import com.glela.common.util.DateUtil;
import com.glela.common.util.GsonUtil;
import com.glela.common.util.ListUtils;
import com.glela.common.util.OrderUtil;
import com.glela.common.util.YeePayAESUtil;
import com.glela.company.model.XzNotifyLog;
import com.glela.company.model.XzOmsLog;
import com.glela.company.service.XzNotifyLogService;
import com.glela.company.service.XzOmsLogService;
import com.glela.goods.mapper.GoodsExtendedAttributeMapper;
import com.glela.goods.model.GoodsExtends;
import com.glela.goods.service.AnswerQuestionService;
import com.glela.goods.service.GoodsNosendRegionService;
import com.glela.goods.service.ShoppingCartService;
import com.glela.mq.service.OrderQueueService;
import com.glela.order.model.ExpressCompany;
import com.glela.order.model.LogisticsStatus;
import com.glela.order.model.OrderDetail;
import com.glela.order.model.OrderObject;
import com.glela.order.model.OrderPay;
import com.glela.order.model.PayTypeConfig;
import com.glela.order.model.request.RequestAfterSalesModel;
import com.glela.order.model.request.RequestGetOrderObject;
import com.glela.order.model.request.RequestOrderDetail;
import com.glela.order.model.response.OrderInfoVo;
import com.glela.order.model.response.OrderObjectVo;
import com.glela.order.model.response.RespAddOrderInfo;
import com.glela.order.model.response.ResponseOrderNum;
import com.glela.order.model.response.ResponseReason;
import com.glela.order.model.response.ResponseShopOrderNum;
import com.glela.order.model.vo.order.ErrorMsgGoods;
import com.glela.order.service.LogisticsStatusService;
import com.glela.order.service.OrderObjectService;
import com.glela.order.service.OrderPayService;
import com.glela.order.service.OrderService;
import com.glela.order.vo.PollingConfig;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.BaseRestrictions;
import com.glela.platform.model.User;
import com.glela.platform.model.UserAddress;
import com.glela.platform.model.UserPayInfo;
import com.glela.platform.model.request.ReqHeaderVo;
import com.glela.platform.model.request.RequestPageBaseModel;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.model.response.ResponseUser;
import com.glela.platform.service.BaseRestrictionsService;
import com.glela.platform.service.UserAddressService;
import com.glela.platform.service.UserPayInfoService;
import com.glela.platform.service.UserService;
import com.glela.platform.util.ParameterUtils;

/**
 * @author liujie
 * @2016年10月25日
 */
@Controller
@RequestMapping("/order")
public class OrderController extends BaseController {
	private static Logger			logger			= LoggerFactory.getLogger(OrderController.class);
	private static ExecutorService	executorService	= Executors.newFixedThreadPool(10);

	@Autowired
	private Map<String, OrderService>	orderServiceMap;
	@Autowired
	private UserService					userService;
	@Autowired
	private LogisticsStatusService		logisticsStatusService;
	@Autowired
	private OrderObjectService			orderObjectService;
	//	@Autowired
	//	private XzOmsLogService XzOmsLogService;
	@Autowired
	private XzNotifyLogService	xzNotifyLogService;
	@Autowired
	private XzOmsLogService		xzOmsLogService;
	@Autowired
	private OrderPayService		orderPayService;

	@Autowired
	private ShoppingCartService		shoppingCartService;
	@Autowired
	private BaseRestrictionsService	baseRestrictionsService;

	@Autowired
	RedisUtil redisUtil;

	@Autowired
	UserPayInfoService userPayInfoService;

	@Autowired
	private OrderQueueService orderQueueService;

	@Autowired
	private AnswerQuestionService answerQuestionService;
	@Autowired
	private GoodsExtendedAttributeMapper goodsExtendedAttributeMapper;

	@Autowired
	private UserAddressService userAddressService;
	//	private OrderService getOrderService() {
	//		return getOrderService("orderService");
	//	}

	@Autowired
	private GoodsNosendRegionService goodsNosendRegionService;
	
	private OrderService getOrderService2() {
		return getOrderService("orderService2");
	}

	//	private OrderService getOrderService3() {
	//		return getOrderService("orderService3");
	//	}

	//	private OrderService getOrderService4() {
	//		return getOrderService("orderService4");
	//	}
	
	
	private OrderService getOrderService5() {
		return getOrderService("orderService5");
	}

	private OrderService getOrderService(String orderServiceName) {
		return orderServiceMap.get(orderServiceName);
	}

	@RequestMapping(value = "/getOrderObject", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getOrderObject(@RequestBody RequestGetOrderObject requestGetOrderObject) {
		return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20002), HttpStatus.OK);
		//		try {
		//			if (ParameterUtils.validParams(requestGetOrderObject.getUserId(), requestGetOrderObject.getGoodsSimpleVoList()) || requestGetOrderObject.getGoodsSimpleVoList().size() == 0) {
		//				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
		//			}
		//			ResponseGetOrderObject responseGetOrderObject = getOrderService2().getOrderObject(requestGetOrderObject);
		//			if (responseGetOrderObject == null) {
		//				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20800), HttpStatus.OK);
		//			}
		//			return new ResponseEntity<>(new ResponseResultModel<>(responseGetOrderObject), HttpStatus.OK);
		//		} catch (PlatformException pe) {
		//			logger.error(pe.getMessage(), pe);
		//			return new ResponseEntity<>(new ResponseBaseModel(pe.getErrorEnum(), pe.getMessage()), HttpStatus.OK);
		//		} catch (Exception e) {
		//			logger.error(e.getMessage(), e);
		//			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		//		}
	}

	/** 订单结算 */
	@RequestMapping(value = "/addOrderObject", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> addOrderObject(@RequestBody RequestOrderDetail requestOrderDetail) {
		return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20002), HttpStatus.OK);
		//		try {
		//			//校验商品明细，支付方式、配送类型不能为空
		//			if (ParameterUtils.validParams(requestOrderDetail.getOrderDetailList(), requestOrderDetail.getPayType(), requestOrderDetail.getDeliveryWay()) || requestOrderDetail.getOrderDetailList().size() == 0) {
		//				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
		//			}
		//			//不是到店取且收货地址为空，提示缺少参数
		//			if (requestOrderDetail.getDeliveryWay().intValue() != 2 && ParameterUtils.validParams(requestOrderDetail.getMemberDeliveryAddressId())) {
		//				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
		//			}
		//
		//			//生成结算单
		//			String result = getOrderService2().addOrderObject(requestOrderDetail);
		//			if (result == null) {
		//				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20800), HttpStatus.OK);
		//			} else if (result.equals("")) {
		//				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		//			} else {
		//				return new ResponseEntity<>(new ResponseResultModel<>(result), HttpStatus.OK);
		//			}
		//		} catch (PlatformException pe) {
		//			logger.error(pe.getMessage(), pe);
		//			return new ResponseEntity<>(new ResponseBaseModel(pe.getErrorEnum(), pe.getMessage()), HttpStatus.OK);
		//		} catch (Exception e) {
		//			logger.error(e.getMessage(), e);
		//			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		//		}
	}

	/** 订单优惠券 */
	@RequestMapping(value = "orderAvlRedPacket", method = RequestMethod.POST)
	public @ResponseBody ResponseEntity<?> getUserRedPacket(@RequestBody RequestGetOrderObject reqGetOrderObject, HttpServletRequest request) {
		try {
			reqGetOrderObject.initHeader(request);
			ReqHeaderVo reqHeader = reqGetOrderObject.getReqHeader();
			if (ParameterUtils.validParams(reqGetOrderObject.getUserId()) || StringUtils.isAnyBlank(reqHeader.getAppSystemVersion(), reqHeader.getPhoneType())) {
				logger.warn("订单可用优惠券接口参数缺少：用户id为空", reqGetOrderObject.getUserId());
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			return new ResponseEntity<>(getOrderService5().getAvlRedPacketList(reqGetOrderObject), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("订单去结算失败：{}", e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * <dl>
	 * <dt>获取订单去结算信息</dt>
	 * </dl>
	 * @param reqGetOrderObject
	 * @return ResponseEntity<?>
	 * @author zls
	 * @date 2017年7月20日 下午4:38:06
	 */
	@RequestMapping(value = "getOrderInfo", method = RequestMethod.POST)
	public @ResponseBody ResponseEntity<?> getOrderInfo(@RequestBody RequestGetOrderObject reqGetOrderObject, HttpServletRequest request) {
		long currentTimeMillis = System.currentTimeMillis();
		try {
			reqGetOrderObject.initHeader(request);
			if (ParameterUtils.validParams(reqGetOrderObject.getUserId(), reqGetOrderObject.getGoodsSimpleVoList()) || reqGetOrderObject.getGoodsSimpleVoList().size() == 0) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			ReqHeaderVo reqHeader = reqGetOrderObject.getReqHeader();
			if (StringUtils.isAnyBlank(reqHeader.getPhoneType(), reqHeader.getAppSystemVersion())) {
				logger.error("订单结算页版本信息不全：[{}-{}]", reqHeader.getPhoneType(), reqHeader.getAppSystemVersion());
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			//						reqGetOrderObject.setToken(TokenProcessor.getInstance().generateToken(request));
			return new ResponseEntity<>(getOrderService5().getToOrderInfo(reqGetOrderObject), HttpStatus.OK);
		} catch (DataIntegrityViolationException e) {
			logger.error("订单去结算失败：{}-{}", e.getMessage(), JSONObject.toJSONString(reqGetOrderObject));
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20107, "数据偷渡到火星了，请联系客服遣返"), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("订单去结算失败：{}", e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		} finally {
			if (logger.isInfoEnabled()) {
				logger.info("订单确认页耗时：{}-{}", System.currentTimeMillis() - currentTimeMillis, getClientType(request));
			}
		}
	}

	/** 客户端类型 */
	private String getClientType(HttpServletRequest request) {
		return request.getHeader("phoneType");
	}

	/** 生成交易订单 */
	@RequestMapping(value = "/addOrderInfo", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> addOrderInfo(@RequestBody final RequestOrderDetail reqOrderDetail, HttpServletRequest request) {
		long currentTimeMillis = System.currentTimeMillis();
		Long incr = 0l;
		try {
			reqOrderDetail.initHeader(request);
			if (true) { //暂时把这里设置为TRUE， 所有客户端均在这里进行能否下单的判断
				Map<String, Object> ret = null;
				try {
					ret = getOrderService2().canOrder(reqOrderDetail);
				} catch (Exception e) {
					logger.error("校验iOS是否可支付异常{}", e.getMessage());
				}
				if (MapUtils.getIntValue(ret, "canOrder", 0) == 0) {
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000, "亲,抢购太火爆请稍后再试..."), HttpStatus.OK);
				}
				if (MapUtils.getIntValue(ret, "canOverSea", 0) == 0) {
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20429), HttpStatus.OK);
				}
			}
			//校验商品明细，支付方式、配送类型不能为空
			if (CollectionUtils.isEmpty(reqOrderDetail.getOrderDetailList())) {
				logger.warn("用户[{}]下单商品明细为空", reqOrderDetail.getUserId());
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if (ParameterUtils.validParams(reqOrderDetail.getToken(), reqOrderDetail.getMemberDeliveryAddressId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			//						if (!orderTokenService.isTokenValid(reqOrderDetail.getToken())) {
			//							return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20001), HttpStatus.OK);
			//						}
			try {
				incr = redisUtil.incr(RedisKeys.ORDER_ADD_COUNT);
			} catch (Exception e) {
				logger.warn("统计下单次数，下单加1失败：{}", e.getMessage());
			}
			final ResponseResultModel<RespAddOrderInfo> addOrderInfo = getOrderService5().addOrderInfo(reqOrderDetail);
			if (addOrderInfo.getData().isClearCart()) {
				//清除购物车
				executorService.submit(new Runnable() {
					@Override
					public void run() {
						shoppingCartService.updateRemoveShoppingCart(userService.selectUserRoleById(reqOrderDetail.getUserId()), addOrderInfo.getData().getpId());
					}
				});
			}
			return new ResponseEntity<>(addOrderInfo, HttpStatus.OK);
		} catch (PlatformException pe) {
			logger.error("生成交易单失败：{}-{}:{}", pe.getMessage(), reqOrderDetail.getToken());
			return new ResponseEntity<>(new ResponseBaseModel(pe.getErrorEnum(), pe.getMessage()), HttpStatus.OK);
		} catch (DataIntegrityViolationException e) {
			logger.error("订单生成结算单失败：{}-{}:{}", e.getMessage(), reqOrderDetail.getToken(), JSONObject.toJSONString(reqOrderDetail), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20107, "数据偷渡到火星了，请联系客服遣返"), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("订单生成结算单失败：{}-{}:{}", e.getMessage(), reqOrderDetail.getToken(), JSONObject.toJSONString(reqOrderDetail), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		} finally {
			if (incr != null && incr > 0) {
				try {
					redisUtil.decr(RedisKeys.ORDER_ADD_COUNT);
				} catch (Exception e) {
					logger.warn("统计下单次数，下单成功减一失败：{}", e.getMessage());
				}
			}
			if (logger.isInfoEnabled()) {
				logger.info("同步下单耗时：{}-{}", System.currentTimeMillis() - currentTimeMillis, getClientType(request));
			}
		}
	}

	//	private static Map<String, int[]> appVersionMap = new LinkedHashMap<>();

	//	private OrderService getOrderServiceAppVersion(String phoneType, String appVersion) {
	//		OrderService orderService = getOrderService4();
	//		try {
	//			if (StringUtils.isBlank(appVersion)) {
	//				return orderService;
	//			}
	//			int[] versions = appVersionMap.get(appVersion);
	//			if (ArrayUtils.isEmpty(versions)) {
	//				String[] split = StringUtils.split(appVersion, ".");
	//				versions = new int[split.length];
	//				for (int i = 0; i < split.length; i++) {
	//					versions[i] = NumberUtils.toInt(split[i]);
	//				}
	//				appVersionMap.put(appVersion, versions);
	//			}
	//			boolean newVersion = true;
	//			for (int i = 0; i < versions.length; i++) {
	//				if (!newVersion) {
	//					break;
	//				}
	//				switch (i) {
	//					case 0:
	//						newVersion = versions[i] >= 5;
	//						break;
	//					case 1:
	//						newVersion = versions[i] >= 4;
	//						break;
	//					case 2:
	//						newVersion = versions[i] >= 0;
	//						break;
	//
	//					default:
	//						newVersion = false;
	//						break;
	//				}
	//			}
	//			if (newVersion) {
	//				orderService = getOrderService5();
	//			}
	//		} catch (Exception e) {}
	//		return orderService;
	//	}

	@RequestMapping(value = "alipayNotify", method = RequestMethod.POST)
	@ResponseBody
	public String alipayNotify(HttpServletRequest request, HttpServletResponse response) {
		try {
			logger.info("trade_status=" + request.getParameter("trade_status") + ",out_trade_no=" + request.getParameter("out_trade_no"));
			// Map requestParamMap = request.getParameterMap();
			// if(requestParamMap!=null)
			// {
			// logger.info("requestParamMap="+requestParamMap.toString());
			// }
			Map<String, String> params = new HashMap<String, String>();
			Enumeration<String> requestParams = request.getParameterNames();
			if (requestParams != null) {
				logger.info("alipayNotify requestParams=" + requestParams.toString());
			} else {
				logger.info("alipayNotify requestParams=null");
			}
			int i = 0;
			while (requestParams.hasMoreElements()) {
				String name = requestParams.nextElement().toString();
				if (i == 0) {
					logger.info("alipayNotify requestParams0=" + name + ",value=" + request.getParameter(name));
				}
				if (!name.equals("sign") && !name.equals("sign_type")) {
					params.put(name, request.getParameter(name));
				}
				i++;
			}
			if (params.size() == 0) {
				logger.error(" signVerified=params.size()==0");
				return "failure";
			}
			logger.info("alipayNotify params=" + params.toString());
			// AlipayAppKeyInfo
			// alipayAppKeyInfo=orderService2.getAlipayAppKeyInfo();
			// boolean signVerified = AlipaySignature.rsaCheckV1(params,
			// alipayAppKeyInfo.getAlipayPublicKey(), Alipay.CHARSET);
			boolean signVerified = true;
			if (signVerified) {
				String tradeStatus = request.getParameter("trade_status");
				if ("TRADE_FINISHED".equals(tradeStatus) || "TRADE_SUCCESS".equals(tradeStatus)) {
					String orderSn = request.getParameter("out_trade_no");
					int payType = PayTypeEnum.T2.getCode();
					int paymentFee = 0;
					double fee = Double.parseDouble(request.getParameter("total_fee"));
					paymentFee = (int) (fee * 100);
					String payId = request.getParameter("trade_no");
					getOrderService2().updatePayOrderInfo(orderSn, payType, paymentFee, payId);

					orderForXZOMS(orderSn, payId, payType, orderSn);
					logger.info(orderSn + " signVerified=" + signVerified);
					calculateUserRole(orderSn);
					return "success";
				} else {
					return "failure";
				}
			} else {
				logger.error(" signVerified=" + signVerified);
				return "failure";
			}
		} catch (PlatformException e) {
			logger.error("alipayNotify error:" + e.getMessage(), e);
			return "failure";
		} catch (Exception e) {
			logger.error("alipayNotify error:" + e.getMessage(), e);
			return "failure";
		}
	}

	@RequestMapping(value = "alipayNotify/{orderSn}/{payNo}")
	public @ResponseBody String alipayNotifyByOrderSn(@PathVariable("orderSn") String orderSn, @PathVariable("payNo") String payNo, HttpServletRequest request, HttpServletResponse response) {
		try {
			Map<String, String> dataParamsMap = new HashMap<String, String>();
			Enumeration<String> requestParams = request.getParameterNames();
			while (requestParams.hasMoreElements()) {
				String name = requestParams.nextElement().toString();
				dataParamsMap.put(name, request.getParameter(name));
			}
			if (MapUtils.isEmpty(dataParamsMap)) {
				logger.error("支付宝回调通知参数{}-{} 为空", orderSn, payNo);
				return BaseConstants.FAILURE;
			}
			logger.warn("支付宝回调通知参数{}-{}:{}", orderSn, payNo, JSON.toJSONString(dataParamsMap));

			String tradeStatus = MapUtils.getString(dataParamsMap, "trade_status");
			if (StringUtils.equalsAny(tradeStatus, "TRADE_SUCCESS", "TRADE_FINISHED")) {//支付成功或交易完成
				String out_trade_no = request.getParameter("out_trade_no");
				if (!StringUtils.equals(payNo, out_trade_no)) {
					logger.warn("支付宝回调通知非法订单{}-原支付号{}:通知支付号{}", orderSn, payNo, out_trade_no);
					return BaseConstants.FAILURE;
				}

				OrderPay checkOrderPay = orderPayService.selectByPaySn(payNo);
				if (checkOrderPay == null || checkOrderPay.getPayType() != PayTypeEnum.T2.getCode().intValue()) {
					logger.warn("支付宝回调通知非法订单{}-原支付号{}:通知支付号{}:不存在此支付记录或支付类型不符", orderSn, payNo, out_trade_no);
					return BaseConstants.FAILURE;
				}
				if (!StringUtils.equals(orderSn, checkOrderPay.getOrderSn())) {
					logger.warn("支付宝回调通知非法订单{}-原支付号{}:通知支付订单{}-通知支付号{}", orderSn, payNo, checkOrderPay.getOrderSn(), out_trade_no);
					return BaseConstants.FAILURE;
				}
				if (checkOrderPay.getStatus() == 1) {//已支付
					logger.warn("支付宝回调通知：{}-{}:重复通知", orderSn, payNo);
					return BaseConstants.success;
				}

				long paymentFee = 0;
				double fee = NumberUtils.toDouble(request.getParameter("total_fee"), -1);
				paymentFee = Math.round(fee * 100);
				if (checkOrderPay.getTotalFee() != paymentFee) {
					logger.warn("支付宝回调通知非法订单{}-原支付号{}:通知支付号{}:应付金额{}与通知实付金额{}不等", orderSn, payNo, out_trade_no, checkOrderPay.getTotalFee(), paymentFee);
					return BaseConstants.FAILURE;
				}

				//支付成功，金额相匹配，更新订单信息
				String payId = request.getParameter("trade_no");

				checkOrderPay.setExternalId(payId);
				checkOrderPay.setPayTime(MapUtils.getString(dataParamsMap, "gmt_payment", DateUtil.getNow()));
				getOrderService2().updatePayOrderInfo(orderSn, checkOrderPay, paymentFee, payId);
				//添加消息队列
				getOrderService2().addMQPayCallBack(orderSn);
				calculateUserRole(orderSn);
				return BaseConstants.success;
			} else if (StringUtils.equals(tradeStatus, "WAIT_BUYER_PAY")) {//交易创建，等待买家付款
				logger.warn("支付宝回调通知：{}-{}:交易创建，等待买家付款{}", orderSn, payNo, tradeStatus);
				return BaseConstants.success;
			} else if (StringUtils.equals(tradeStatus, "TRADE_CLOSED")) {//未付款交易超时关闭，或支付完成后全额退款
				logger.warn("支付宝回调通知：{}-{}:未付款交易超时关闭，或支付完成后全额退款{}-{}", orderSn, payNo, tradeStatus, MapUtils.getString(dataParamsMap, "refund_status"));
				return BaseConstants.success;
			}
		} catch (PlatformException e) {
			logger.error("支付宝直连通知失败:{}-{}:{}-{}", orderSn, payNo, e.getErrorEnum().getCode(), e.getMessage());
		} catch (Exception e) {
			logger.error("支付宝直连通知失败:{}-{}:{}", orderSn, payNo, e.getMessage(), e);
		}
		return "failure";
	}

	/**
	 * MaoZeYao
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "alipayNotifyVip", method = RequestMethod.POST)
	@ResponseBody
	public String alipayNotifyVip(HttpServletRequest request, HttpServletResponse response) {
		try {
			logger.info("alipayNotifyVip trade_status=" + request.getParameter("trade_status") + ",out_trade_no=" + request.getParameter("out_trade_no"));
			// Map requestParamMap = request.getParameterMap();
			// if(requestParamMap!=null)
			// {
			// logger.info("requestParamMap="+requestParamMap.toString());
			// }
			Map<String, String> params = new HashMap<String, String>();
			Enumeration<String> requestParams = request.getParameterNames();
			if (requestParams != null) {
				logger.info("alipayNotifyVip requestParams=" + requestParams.toString());
			} else {
				logger.info("alipayNotifyVip requestParams=null");
			}
			int i = 0;
			while (requestParams.hasMoreElements()) {
				String name = requestParams.nextElement().toString();
				if (i == 0) {
					logger.info("alipayNotifyVip requestParams0=" + name + ",value=" + request.getParameter(name));
				}
				if (!name.equals("sign") && !name.equals("sign_type")) {
					params.put(name, request.getParameter(name));
				}
				i++;
			}
			if (params.size() == 0) {
				logger.error("alipayNotifyVip signVerified=params.size()==0");
				return "failure";
			}
			logger.info("alipayNotifyVip params=" + params.toString());
			// AlipayAppKeyInfo
			// alipayAppKeyInfo=orderService2.getAlipayAppKeyInfo();
			// boolean signVerified = AlipaySignature.rsaCheckV1(params,
			// alipayAppKeyInfo.getAlipayPublicKey(), Alipay.CHARSET);
			boolean signVerified = true;
			if (signVerified) {
				String tradeStatus = request.getParameter("trade_status");
				if ("TRADE_FINISHED".equals(tradeStatus) || "TRADE_SUCCESS".equals(tradeStatus)) {
					String orderSn = request.getParameter("out_trade_no");
					int payType = PayTypeEnum.T2.getCode();
					int paymentFee = 0;
					double fee = Double.parseDouble(request.getParameter("total_fee"));
					paymentFee = (int) (fee * 100);
					String payId = request.getParameter("trade_no");
					// 业务代码
					getOrderService2().confirmOrderVip(orderSn, payType, paymentFee, payId);
					logger.info(orderSn + "alipayNotifyVip signVerified=" + signVerified);
					calculateUserRole(orderSn);
					return "success";
				} else {
					return "failure";
				}
			} else {
				logger.error("alipayNotifyVip signVerified=" + signVerified);
				return "failure";
			}
		} catch (PlatformException e) {
			logger.error("alipayNotifyVip error:" + e.getMessage(), e);
			return "failure";
		} catch (Exception e) {
			logger.error("alipayNotifyVip error:" + e.getMessage(), e);
			return "failure";
		}
	}

	@RequestMapping(value = "/selectValidPayTypeConfig", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> selectValidPayTypeConfig(@RequestBody YeePayBaseRequest yeePayBaseRequest, HttpServletRequest request) {
		try {
			List<PayTypeConfig> payTypeConfigList = getOrderService2().selectPayTypeConfigByStatus(StatusEnum.S1.getCode());
			return new ResponseEntity<>(new ResponseResultModel<>(payTypeConfigList), HttpStatus.OK);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	private void orderForXZNotifyLog(final String requestid, final String result) {
		Runnable task = new Runnable() {
			// @Override
			@Override
			public void run() {
				XzNotifyLog xzNotifyLog = new XzNotifyLog();
				xzNotifyLog.setOrderSn(requestid);
				xzNotifyLog.setResult(result);
				xzNotifyLogService.insertSelective(xzNotifyLog);
			}
		};
		executorService.submit(task);
	}

	@RequestMapping(value = "yeePayWebCallBack", method = RequestMethod.GET)
	public ModelAndView yeePayWebCallBack(HttpServletRequest request, HttpServletResponse response) {
		String getData = request.getParameter("data");
		String result = YeePayAESUtil.decrypt(getData, YeePay.SECRET_KEY.substring(0, 16));
		//JSONObject requestJson = JSONObject.parseObject(result);
		//String H5_PAY_CALLBACK_PAGE = "http://h5.xzhuang.com/order/index.html?deliver=deliver";//默认不是开店单，跳转至一般支付成功页
		String H5_PAY_CALLBACK_PAGE =baseRestrictionsService.selectAllBaseRestrictionsByType("H5_PAY_CALLBACK_PAGE").getName();
		try {
			JSONObject requestJson = JSONObject.parseObject(result);
			if (requestJson != null && StringUtils.isNotBlank(requestJson.getString("requestid"))) {
				if (orderObjectService.isOpenStoreOrder(requestJson.getString("requestid"))) {
					H5_PAY_CALLBACK_PAGE =baseRestrictionsService.selectAllBaseRestrictionsByType("H5_PAY_CALLBACK_PAGE_OPENSTORE").getName();
				}
			}

		} catch (Exception e) {
			logger.error("解析易宝WEBCALLBACK参数错误, 参数 : {} ", result);
		}

		return new ModelAndView("redirect:" + H5_PAY_CALLBACK_PAGE);
		//		logger.error(" 易宝WEBCALLBACK 参数内容:  {}" , result);
		//
		//		String meg = "<!DOCTYPE html>" + " <html>" + "<head>" + "   <meta charset=\"utf-8\">" + "   <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=\">" + "   <title>支付成功</title>" + "</head>" + "<body>" + "   " + "    <header>" + "   <h1>支付成功</h1>" + "    </header>" + "    " + "    <nav>" + "   <ul>" + "  <li id=\"home\">Thanks</li>" + "   </ul>" + "    </nav>" + "  " + "    <section>" + "   <h1>友情提醒</h1>" + "   <article>" + "  <p>您的订单已支付成功，谨防诈骗" + "小铺来了不会以任何形式及理由，让您通过支付宝、微信、银行、或者ATM机进行转账或要求您点击链接进行退款或重新支付，有关订单售后问题，您可致电4000369090" + "</p>" + "  " + "   </article>" + "    </section>" + "  " + "    <footer>" + "  " + "    </footer>" + "</body>" + " </html>";
		//
		//		return meg;
	}

	/**
	 * MaoZeYao 2016-12-14 update by liujie 2016-12-16 易宝网银支付回调
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "yeePayNetServerNotify", method = RequestMethod.GET)
	@ResponseBody
	public String yeePayNetServerNotify(HttpServletRequest request, HttpServletResponse response) {
		String result = null;
		String requestid = null;
		try {
			String getData = request.getParameter("data");
			result = YeePayAESUtil.decrypt(getData, YeePay.SECRET_KEY.substring(0, 16));
			JSONObject requestJson = JSONObject.parseObject(result);

			//			String customernumber = requestJson.getString("customernumber"); // 商户编号
			requestid = requestJson.getString("requestid"); // 自己的订单号
			String code = requestJson.getString("code"); // 交易成功的返回值为1
			//			String notifytype = requestJson.getString("notifytype"); // 通知类型
			String externalid = requestJson.getString("externalid"); // 易宝的交易凭证
			String amount = requestJson.getString("amount"); // 金额  元
			//			String bankcode = requestJson.getString("bankcode"); // 银行编码
			//			String cardtype = requestJson.getString("cardtype"); // 银行卡类别
			//			String paydate = requestJson.getString("paydate"); // 支付时间
			String payProduct = requestJson.getString("payProduct"); // 支付方式
			// String hmac = requestJson.getString("hmac");
			// String cardno = requestJson.getString("cardno"); // 卡后四位
			//			if (StringUtils.isEmpty(payProduct)) {
			//				logger.error("易宝支付回调接口失败：参数payProduct为空-{}", result);
			//				return "payProduct is empty.";
			//			}

			if (code.equals("1")) {
				String orderSn = requestid;
				int payType = 0;
				if (StringUtils.isBlank(payProduct)) {//张云飞 8月30日修改， 易宝确认 payProduct 新版支付，该字段为非必填字段
					OrderObject orderObject = getOrderService2().selectOrderObjectByOrderSn(orderSn);
					payType = orderObject.getPayType();
				} else {
					if (payProduct.equals("WECHATG")) {
						payType = PayTypeEnum.T22.getCode();
					} else if (payProduct.equals("WECHAT_APP")) {
						payType = PayTypeEnum.T20.getCode();
					} else if (payProduct.equals("ALIPAY_APP")) {
						payType = PayTypeEnum.T21.getCode();
					} else if (payProduct.equals("ONEKEY")) {
						payType = PayTypeEnum.T23.getCode();
					} else if (payProduct.equals("ONEKEY_NORMAL")) {
						payType = PayTypeEnum.T23.getCode();
					} else if (payProduct.equals("WAP-ZHT")) {
						payType = PayTypeEnum.T23.getCode();
					} else if (payProduct.equals("WECHATU")) {
						payType = PayTypeEnum.T24.getCode();
					}
					if (payType == 0) {
						OrderObject orderObject = getOrderService2().selectOrderObjectByOrderSn(orderSn);
						payType = orderObject.getPayType();
						if (payType == 0) {
							payType = PayTypeEnum.T23.getCode();
						}
					}
				}
				int paymentFee = Double.valueOf(Double.parseDouble(amount) * 100).intValue();
				String payId = externalid;
				getOrderService2().updatePayOrderInfo(orderSn, payType, paymentFee, payId);
				//				divide(orderSn);
				//				orderForXZOMS(orderSn, payId, payType, orderSn);
				logger.info("yeePayNetServerNotify SUCCESS:" + orderSn);
				orderForXZNotifyLog(requestid, "SUCCESS:" + result);
				calculateUserRole(orderSn);
				return BaseConstants.success;
			} else {
				logger.error(result);
				logger.error("yeePayNetServerNotify fail");
				orderForXZNotifyLog(requestid, "返回值code非1FAIL:" + result);
				return "FAIL";
			}
		} catch (Exception e) {
			logger.error("yeePayNetServerNotify FAIL:" + e.getMessage(), e);
			orderForXZNotifyLog(requestid, "RUNTIME-FAIL:" + result);
			return "FAIL";
		}
	}

	@RequestMapping(value = "wechatPublicNotify")
	public @ResponseBody String wechatPublicNotify(HttpServletRequest request, HttpServletResponse response) {
		try {
			Map<String, Object> map = PaymentUtil.getWeChatNodityByXml(request.getInputStream());
			logger.info("wechatPublicNotify map=" + map.toString());
			if (map.get("result_code").equals("SUCCESS")) {
				String orderSn = map.get("out_trade_no").toString();
				String tradeType = map.get("trade_type").toString();
				int payType = PayTypeEnum.T3.getCode();
				if (tradeType.equals("APP")) {
					payType = PayTypeEnum.T1.getCode();
				}
				int paymentFee = Integer.parseInt(map.get("cash_fee").toString());
				String payId = map.get("transaction_id").toString();
				getOrderService2().updatePayOrderInfo(orderSn, payType, paymentFee, payId);

				//								orderForXZOMS(orderSn, payId, payType, orderSn);
				logger.info("wechatPublicNotify succuss:" + orderSn);
				calculateUserRole(orderSn);
				return WeChat.SUCCESS_XML;
			} else {
				logger.error("wechatPublicNotify fail");
				return WeChat.FAIL_XML;
			}
		} catch (PlatformException e) {
			logger.error("wechatPublicNotify error:" + e.getMessage(), e);
			return WeChat.FAIL_XML;
		} catch (Exception e) {
			logger.error("wechatPublicNotify error:" + e.getMessage(), e);
			return WeChat.FAIL_XML;
		}
	}

	@RequestMapping(value = "wechatPublicNotify/{orderSn}/{payNo}")
	public @ResponseBody String wechatPublicNotifyByOrderSn(@PathVariable("orderSn") String orderSn, @PathVariable("payNo") String payNo, HttpServletRequest request, HttpServletResponse response) {
		try {
			Map<String, Object> map = PaymentUtil.getWeChatNodityByXml(request.getInputStream());
			logger.warn("微信支付通知{}-{}：{}", orderSn, payNo, JSON.toJSONString(map));
			if (StringUtils.equals("SUCCESS", MapUtils.getString(map, "result_code"))) {
				String out_trade_no = map.get("out_trade_no").toString();
				if (!StringUtils.equals(payNo, out_trade_no)) {
					logger.warn("微信支付通知{}-{}：支付流水号{}与原支付流水号不匹配", orderSn, payNo, out_trade_no);
					return WeChat.FAIL_XML;
				}
				OrderPay checkOrderPay = orderPayService.selectByPaySn(payNo);
				if (checkOrderPay == null) {
					logger.warn("微信支付通知{}-{}：支付流水不存在", orderSn, payNo, out_trade_no);
					return WeChat.FAIL_XML;
				}
				if (checkOrderPay.getStatus() == 1) {
					logger.warn("微信支付通知{}-{}：重复通知", orderSn, payNo);
					return WeChat.SUCCESS_XML;
				}

				String tradeType = MapUtils.getString(map, "trade_type");
				int payType = PayTypeEnum.T3.getCode();
				if (StringUtils.equals("APP", tradeType)) {//微信直连支付
					payType = PayTypeEnum.T1.getCode();
				}
				if (payType != checkOrderPay.getPayType()) {
					logger.warn("微信支付通知{}-{}：支付类型不符：原{}：现{}", orderSn, payNo, checkOrderPay.getPayType(), payType);
					return WeChat.FAIL_XML;
				}

				int total_fee = MapUtils.getIntValue(map, "total_fee", 0);
				if (total_fee != checkOrderPay.getTotalFee()) {
					logger.warn("微信支付通知{}-{}：支付金额不符：原{}：现{}", orderSn, payNo, checkOrderPay.getTotalFee(), total_fee);
					return WeChat.FAIL_XML;
				}

				String payId = MapUtils.getString(map, "transaction_id", StringUtils.EMPTY);
				checkOrderPay.setExternalId(payId);
				String payTime = MapUtils.getString(map, "time_end");
				if (StringUtils.isBlank(payTime)) {
					payTime = DateUtil.getNow();
				} else {
					payTime = DateTime.parse(payTime, DateUtil.DATE_FORMATTER_YYYYMMDDHHMMSS).toString(BaseConstants.DATE_FORMAT);
				}
				checkOrderPay.setPayTime(payTime);
				getOrderService2().updatePayOrderInfo(orderSn, checkOrderPay, total_fee, payId);
				//添加消息队列
				getOrderService2().addMQPayCallBack(orderSn);
				calculateUserRole(orderSn);
				return WeChat.SUCCESS_XML;
			} else {
				logger.warn("微信支付通知{}-{}：支付不成功", orderSn, payNo);
				return WeChat.FAIL_XML;
			}
		} catch (PlatformException e) {
			logger.error("wechatPublicNotify error:" + e.getMessage(), e);
			return WeChat.FAIL_XML;
		} catch (Exception e) {
			logger.error("wechatPublicNotify error:" + e.getMessage(), e);
			return WeChat.FAIL_XML;
		}
	}

	/**
	 * MaoZeYao 微信支付VIP回调
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "wechatPublicNotifyVip")
	@ResponseBody
	public String wechatPublicNotifyVip(HttpServletRequest request, HttpServletResponse response) {
		try {
			Map<String, Object> map = PaymentUtil.getWeChatNodityByXml(request.getInputStream());
			logger.info("wechatPublicNotifyVip map=" + map.toString());
			if (map.get("result_code").equals("SUCCESS")) {
				String orderSn = map.get("out_trade_no").toString();
				String tradeType = map.get("trade_type").toString();
				int payType = PayTypeEnum.T3.getCode();
				if (tradeType.equals("APP")) {
					payType = PayTypeEnum.T1.getCode();
				}
				int paymentFee = Integer.parseInt(map.get("cash_fee").toString());
				String payId = map.get("transaction_id").toString();
				// 业务代码
				getOrderService2().confirmOrderVip(orderSn, payType, paymentFee, payId);
				logger.info("wechatPublicNotifyVip succuss:" + orderSn);
				calculateUserRole(orderSn);
				return WeChat.SUCCESS_XML;
			} else {
				logger.error("wechatPublicNotifyVip fail");
				return WeChat.FAIL_XML;
			}
		} catch (PlatformException e) {
			logger.error("wechatPublicNotifyVip error:" + e.getMessage(), e);
			return WeChat.FAIL_XML;
		} catch (Exception e) {
			logger.error("wechatPublicNotifyVip error:" + e.getMessage(), e);
			return WeChat.FAIL_XML;
		}
	}

	/** 异步推送订单到oms */
	private void orderForXZOMS(final String orderSn, final String payId, final Integer payType, final String t_id) {
		Runnable task = new Runnable() {
			// @Override
			@Override
			public void run() {
				try {
					getOrderService2().updateOrderForXZOMS(orderSn, payId, payType, t_id);
				} catch (PlatformException e) {
					logger.error("订单[{}]推送OMS异常：{}", orderSn, e.getMessage(), e);
					XzOmsLog xzOmsLog = new XzOmsLog();
					xzOmsLog.setOrderSn(orderSn);
					xzOmsLog.setOrderInfoSn(null);
					xzOmsLog.setResult(StringUtils.substring(e.getMessage(), 0, 25));
					xzOmsLogService.insertSelective(xzOmsLog);
				}
			}
		};
		executorService.submit(task);
	}

	//	private void divide(final String orderSn) {
	//		Runnable task = new Runnable() {
	//			// @Override
	//			@Override
	//			public void run() {
	//				try {
	//					Thread.sleep(180000);
	//					getOrderService2().divide(orderSn);
	//				} catch (Exception e) {
	//					// TODO Auto-generated catch block
	//					logger.error(e.getMessage(), e);
	//				}
	//			}
	//		};
	//		executorService.submit(task);
	//	}

	/**
	 * 推送暴露接口
	 * 
	 * @author 程泽权
	 * 
	 * @param requestGetOrderObject
	 * @return
	 */
	@RequestMapping(value = "/orderForXZOMS", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> orderForXZOMS(@RequestBody RequestGetOrderObject requestGetOrderObject) {
		try {
			if (ParameterUtils.validParams(requestGetOrderObject.getOrderSn())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			OrderObjectVo orderObjectVo = orderObjectService.getOrderObjectEntityByOrderSnTwo(requestGetOrderObject.getOrderSn());
			if (orderObjectVo.getPayType().intValue() == 0) {
				orderObjectVo.setPayType(PayTypeEnum.T23.getCode());
			}
			// 运行前先删除一次
			//			XzOmsLogService.deleteByPrimaryOrderSn(orderObjectVo.getOrderSn());
			getOrderService2().updateOrderForXZOMS(orderObjectVo.getOrderSn(), orderObjectVo.getPayId(), orderObjectVo.getPayType(), orderObjectVo.getOrderSn());
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 自动推送
	 */
	//	@Scheduled(cron = "0 0/2 * * * ? ")//每五秒钟触发一次
	//	//@Scheduled(cron = "0 0 0 * * ?")//每天晚上12点触发一次
	//	public void selfMotionPush(){
	//		List<String> listString = XzOmsLogService.selectAutoPushOrder();
	//		for(String orderSn:listString){
	//			OrderObjectVo orderObjectVo = orderObjectService.getOrderObjectEntityByOrderSnTwo(orderSn);
	//			if (orderObjectVo.getPayType().intValue() == 0) {
	//				orderObjectVo.setPayType(PayTypeEnum.T23.getCode());
	//			}
	//			// 运行前先删除一次
	//			XzOmsLogService.deleteByPrimaryOrderSn(orderObjectVo.getOrderSn());
	//			orderService2.orderForXZOMS(orderObjectVo.getOrderSn(), orderObjectVo.getPayId(),
	//					orderObjectVo.getPayType());
	//		}
	//	}

	/**
	 * 清分
	 * 
	 * @author 程泽权
	 * 
	 * @param requestGetOrderObject
	 * @return
	 */
	@RequestMapping(value = "/artificialEliminate", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> artificialEliminate(@RequestBody RequestGetOrderObject requestGetOrderObject) {
		try {
			if (ParameterUtils.validParams(requestGetOrderObject.getOrderSn())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			getOrderService2().divide(requestGetOrderObject.getOrderSn());
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	//	/**
	//	 * 自动清分
	//	 * @throws Exception 
	//	 */
	//	@Scheduled(cron = "0 0/2 * * * ? ")//每两分钟触发一次
	//	//@Scheduled(cron = "0 0 0 * * ?")//每天晚上12点触发一次
	//	public void selfEliminate() throws Exception{
	//		List<String> listString = orderService.selectOrderClearing();
	//		for(String orderSn:listString){
	//			if(orderSn==null){
	//				continue;
	//			}
	//			orderService.divide(orderSn);
	//		}
	//		}

	@RequestMapping(value = "/orderForXZOMSMany", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> orderForXZOMSMany(@RequestBody RequestGetOrderObject requestGetOrderObject) {
		try {
			if (ParameterUtils.validParams(requestGetOrderObject.getOrderSn())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			for (String orderSn : requestGetOrderObject.getOrderSnList()) {
				try {
					OrderObjectVo orderObjectVo = orderObjectService.getOrderObjectEntityByOrderSnTwo(orderSn);
					if (orderObjectVo.getPayType().intValue() == 0) {
						orderObjectVo.setPayType(PayTypeEnum.T23.getCode());
					}
					//运行前先删除一次
					//				XzOmsLogService.deleteByPrimaryOrderSn(orderObjectVo.getOrderSn());
					getOrderService2().updateOrderForXZOMS(orderObjectVo.getOrderSn(), orderObjectVo.getPayId(), orderObjectVo.getPayType(), orderObjectVo.getOrderSn());
				} catch (Exception e) {
					logger.error(e.getMessage(), e);
				}
			}
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 获取个人页面的订单数量
	 * 
	 * @author 卫耀华 2016-10-27
	 * 
	 * @param requestGetOrderObject
	 * @return
	 */
	@RequestMapping(value = "/getOrderNum", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getOrderNum(@RequestBody RequestGetOrderObject requestGetOrderObject) {
		try {
			if (ParameterUtils.validParams(requestGetOrderObject.getUserId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if (requestGetOrderObject.getUserId() == 0) {
				return new ResponseEntity<>(new ResponseResultModel<>(new ResponseOrderNum()), HttpStatus.OK);
			}
			User user = userService.getUser(requestGetOrderObject.getUserId());
			if (null == user) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20113), HttpStatus.OK);
			}
			ResponseOrderNum responseOrderNum = getOrderService2().getOrderNum(requestGetOrderObject.getUserId());
			return new ResponseEntity<>(new ResponseResultModel<>(responseOrderNum), HttpStatus.OK);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * @Description: 获取我的店铺订单数量（包含所有在该店铺下的订单数量，按照订单分类）
	 * @Author: zhangrenjie
	 * @Date: 2018/1/22 9:34
	 *
	 */
	@RequestMapping(value = "/getShopOrderNum", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getShopOrderNum(@RequestBody RequestGetOrderObject requestGetOrderObject) {
		String rslt = null;
		String tempKey = null;
		try {
			if (ParameterUtils.validParams(requestGetOrderObject.getUserId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			/*if (requestGetOrderObject.getUserId() == 0) {
				return new ResponseEntity<>(new ResponseResultModel<>(new ResponseOrderNum()), HttpStatus.OK);
			}
			User user = userService.getUser(requestGetOrderObject.getUserId());*/
			User user = userService.getUserById(requestGetOrderObject.getUserId());
			if (null == user) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20113), HttpStatus.OK);
			}
			//			ResponseShopOrderNum responseOrderNum = getOrderService2().getShopOrderNum(requestGetOrderObject.getUserId());
			//换成新的接口查询-----2018-02-03
			//			ResponseShopOrderNum responseOrderNum = getOrderService2().getShopOrderNumNew(requestGetOrderObject.getUserId());
			//			if (("1").equals(requestGetOrderObject.getAnswerFlag())){
			//				responseOrderNum.setAnsweredFlag(answerQuestionService.getCountByUid(requestGetOrderObject.getUserId().intValue())>0?"1":"0");
			//			}
			//			return new ResponseEntity<>(new ResponseResultModel<>(responseOrderNum), HttpStatus.OK);
			//按照用户Id加入redis缓存------2018-03-07
			tempKey = getTempCacheKey(requestGetOrderObject.getUserId());
			rslt = queryCacheResult(tempKey);
			if (StringUtils.isEmpty(rslt)) {
				ResponseShopOrderNum responseOrderNum = getOrderService2().getShopOrderNumNew(requestGetOrderObject.getUserId());
				if (("1").equals(requestGetOrderObject.getAnswerFlag())) {
					responseOrderNum.setAnsweredFlag(answerQuestionService.getCountByUid(requestGetOrderObject.getUserId().intValue()) > 0 ? "1" : "0");
				}
				rslt = toResultModelJSONNew(responseOrderNum);
			} else {
				return toRespEntity(rslt);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
		return toRespEntity(toCacheResult(tempKey, rslt, 20));//缓存20秒
	}

	/**
	 * 查询我的订单列表
	 * 
	 * @author 程哲权
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/selectOrderInfoByStatusAndUserId", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> selectOrderInfoByStatusAndUserId(@RequestBody RequestPageBaseModel requestPageBaseModel) {
		try {
			if (ParameterUtils.validParams(requestPageBaseModel.getUserId(), requestPageBaseModel.getStatus(), requestPageBaseModel.getPageNum(), requestPageBaseModel.getPageSize())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			List<OrderInfoVo> orderInfoVoList = getOrderService2().selectOrderInfoByStatusAndUserId(requestPageBaseModel.getUserId(), requestPageBaseModel.getStatus(), requestPageBaseModel.getStartIndex(), requestPageBaseModel.getPageSize());
			return new ResponseEntity<>(new ResponseResultModel<List<OrderInfoVo>>(orderInfoVoList), HttpStatus.OK);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 查询达人订单
	 * 
	 * @author 程哲权
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/listTalentOrderInfo", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> listTalentOrderInfo(@RequestBody RequestPageBaseModel requestPageBaseModel) {
		try {
			if (ParameterUtils.validParams(requestPageBaseModel.getUserId(), requestPageBaseModel.getStatus(), requestPageBaseModel.getPageNum(), requestPageBaseModel.getPageSize())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			List<OrderInfoVo> orderInfoVoList = getOrderService2().listTalentOrderInfo(requestPageBaseModel.getUserId(), requestPageBaseModel.getStatus(), requestPageBaseModel.getStartIndex(), requestPageBaseModel.getPageSize());
			return new ResponseEntity<>(new ResponseResultModel<List<OrderInfoVo>>(orderInfoVoList), HttpStatus.OK);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 根据订单号查询订单信息
	 * 
	 * @author 程哲权
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/getOrderInfoEntityByOrderSn", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getOrderInfoEntityByOrderSn(@RequestBody RequestPageBaseModel requestPageBaseModel) {
		try {
			if (ParameterUtils.validParams(requestPageBaseModel.getOrderSn())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			//			OrderInfoVo orderInfoVo = getOrderService2().getOrderInfoEntityByOrderSn(requestPageBaseModel.getOrderSn(), requestPageBaseModel.getUserId());
			OrderInfoVo orderInfoVo = getOrderService2().getOrderInfoEntityByOrderSnNew(requestPageBaseModel);
			if (orderInfoVo == null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20141), HttpStatus.OK);
			}
			return new ResponseEntity<>(new ResponseResultModel<OrderInfoVo>(orderInfoVo), HttpStatus.OK);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 查询物流
	 * 
	 * @author 程哲权
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/getLogistics", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getLogistics(@RequestBody ResponseReason responseReason) {
		try {
			if (ParameterUtils.validParams(responseReason.getOrderSn())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			return logisticsStatusService.getLogisticsEntity(responseReason.getOrderSn());
		} catch (Exception e) {
			logger.error("查询物流信息异常：{}:{}", responseReason.getOrderSn(), e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 查询物流 售后的
	 * 
	 * @author 程哲权
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/getLogisticsEntityShouhou", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getLogisticsEntityShouhou(@RequestBody ResponseReason responseReason) {
		try {
			if (ParameterUtils.validParams(responseReason.getCom(), responseReason.getNo())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			LogisticsStatus logisticsStatus = logisticsStatusService.getLogisticsEntityShouhou(responseReason.getCom(), responseReason.getNo());
			return new ResponseEntity<>(new ResponseResultModel<LogisticsStatus>(logisticsStatus), HttpStatus.OK);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 查询快递公司所有的
	 * 
	 * @author 程哲权
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/listExpreseCompany", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> listExpreseCompany(@RequestBody ResponseReason responseReason) {
		try {
			List<ExpressCompany> expressCompanyList = getOrderService2().listExpreseCompany();
			return new ResponseEntity<>(new ResponseResultModel<List<ExpressCompany>>(expressCompanyList), HttpStatus.OK);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 取消订单 毛泽尧
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/cancelOrder", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> cancelOrder(@RequestBody RequestAfterSalesModel model) {
		try {
			if (ParameterUtils.validParams(model.getOrderObjectId(), model.getUserId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			return getOrderService2().editCancelOrderByOrderId(model.getOrderObjectId(), model.getUserId());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 确认收货 MaoZeYao
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/confirmOrder", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> confirmOrder(@RequestBody RequestAfterSalesModel model) {
		try {
			if (ParameterUtils.validParams(model.getOrderInfoId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			return getOrderService2().confirmOrder(model.getOrderInfoId());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 嗨购调取接口
	 * 
	 * @param requestUserSet
	 * @returns
	 */
	@ResponseBody
	@RequestMapping(value = "/thirdpartyConsignment", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> thirdpartyConsignment(@RequestBody ResponseReason responseReason) {
		if (ParameterUtils.validParams(responseReason.getAppKey(), responseReason.getData(), responseReason.getSign())) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
		}
		try {
			return getOrderService2().thirdpartyConsignment(responseReason.getAppKey(), responseReason.getData(), responseReason.getSign());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 补充结算信息
	 * 
	 * @param requestUserSet
	 * @returns
	 */
	@ResponseBody
	@RequestMapping(value = "/disposeOrderSettlement", method = RequestMethod.POST, consumes = "application/json")
	public void disposeOrderSettlement(@RequestBody ResponseReason responseReason) {
		getOrderService2().disposeOrderSettlement();
	}

	/**
	 * 
	 * 修改结算信息
	 * 
	 * @param requestUserSet
	 * @returns
	 */
	@ResponseBody
	@RequestMapping(value = "/OrderSettlement", method = RequestMethod.POST, consumes = "application/json")
	public void OrderSettlement(@RequestBody ResponseReason responseReason) {
		getOrderService2().OrderSettlement();
	}

	/**
	 * 
	 * 强行清分= =!
	 * 
	 * @param requestUserSet
	 * @returns
	 */
	@ResponseBody
	@RequestMapping(value = "/OrderSettlementartificialEliminate", method = RequestMethod.POST, consumes = "application/json")
	public void OrderSettlementartificialEliminate(@RequestBody ResponseReason responseReason) {
		getOrderService2().OrderSettlement();
	}

	/** 计算用户角色 */
	private void calculateUserRole(final String orderSn) {
		//		executorService.submit(new Runnable() {
		//			@Override
		//			public void run() {
		//				try {
		//					OrderObject orderObject = getOrderService2().selectOrderObjectByOrderSn(orderSn);
		//					if (orderObject == null) {
		//						return;
		//					}
		//					//计算购买人角色
		//					if (orderObject != null && orderObject.getUserId() != null && orderObject.getOpenStore() != 1) {
		//						User _buyUser = userService.getUser(orderObject.getUserId());
		//						if (_buyUser != null) {
		//							userService.calculateUserRole(orderObject.getUserId(), _buyUser.getRoleId());
		//						}
		//					}
		//					//计算推荐人（店主）角色
		//					List<User> recommendFromUsers = getOrderService2().selectOrderRecommendFromUser(orderObject.getId());
		//					if (recommendFromUsers != null && recommendFromUsers.size() > 0) {
		//						for (User user : recommendFromUsers) {
		//							if (user == null || user.getId() == null || user.getId().longValue() == orderObject.getUserId()) {
		//								//为空或者是购买人跳过
		//								continue;
		//							}
		//							userService.calculateUserRole(user.getId(), user.getRoleId());
		//						}
		//					}
		//				} catch (Exception e) {
		//					logger.error("计算用户角色失败:{}", e.getMessage(), e);
		//				}
		//			}
		//		});
	}

	/**
	 * **********************************************
	 * @Title: yeePayCallBack
	 * @Description: 易宝支付回调接口《新》
	 * @param @param request
	 * @param @param response
	 * @param @return
	 * @return String
	 * @throws @author NingChongQing
	 * @date 2017年8月31日 下午3:21:27 **********************************************
	 */
	@RequestMapping(value = "/yeePayCallBack", method = RequestMethod.GET)
	@ResponseBody
	public String yeePayCallBack(HttpServletRequest request, HttpServletResponse response) {
		String result = null;
		String requestid = null;
		String getData = null;
		try {
			getData = request.getParameter("data");
			//			result = YeePayAESUtil.decrypt(getData, YeePay.SECRET_KEY.substring(0, 16));
			result = getData;
			JSONObject requestJson = JSONObject.parseObject(result);
			requestid = requestJson.getString("requestid"); // 请求支付单号
			String code = requestJson.getString("code"); // 交易成功的返回值为1
			String externalid = requestJson.getString("externalid"); // 易宝的交易凭证
			String amount = requestJson.getString("amount"); // 金额  元
			if (code.equals("1")) {
				// 支付记录
				OrderPay orderPay = this.orderPayService.selectByPaySn(requestid);
				// 支付方式
				int payType = orderPay.getPayType();
				// 父单号
				String orderSn = orderPay.getOrderSn();
				// 实际支付金额
				int paymentFee = Double.valueOf(Double.parseDouble(amount) * 100).intValue();
				// 易宝交易流水号
				String payId = externalid;
				// 查询是否存在成功支付的记录<所有支付方式>
				if (this.orderPayService.selectPaySuccessCountByOrderSn(orderSn) > 0) {
					// TODO 自动生成的方法存根
					OrderObject orderObject = getOrderService2().selectOrderObjectByOrderSn(orderSn);
					if (orderObject == null) {
						throw new PlatformException(ErrorEnum.C21202, ErrorEnum.C21202.getMessage() + "(" + orderSn + ")");
					}
					String ooPayId = orderObject.getPayId() == null ? "" : orderObject.getPayId();
					if (payId.equals(ooPayId)) {// 重复推送
						logger.info("Repeated Push,yeePayCallBack SUCCESS:" + orderSn);
						// 记录日志
						orderForXZNotifyLog(requestid, "Repeated Push,SUCCESS:" + result);
					} else {// 重复支付
						// 修改支付记录为支付成功
						this.orderPayService.modifyPaymentSuccess(orderPay.getPaySn(), DateUtil.getNow());
						logger.info("Repeated Payment,yeePayCallBack SUCCESS:" + orderSn);
						// 记录日志
						orderForXZNotifyLog(requestid, "Repeated Payment,SUCCESS:" + result);
					}
					return "SUCCESS";
				}
				// 修改订单相关信息
				getOrderService2().updatePayOrderInfo(orderSn, payType, paymentFee, payId);
				//添加消息队列
				getOrderService2().addMQPayCallBack(orderSn);
				//订单分账和推送订单 交给定时任务来做
				// 订单分账
				//				divide(orderSn);
				// 往OMS推送订单
				//				orderForXZOMS(orderSn, payId, payType, requestid);
				logger.info("yeePayCallBack SUCCESS:" + orderSn);
				// 记录日志
				orderForXZNotifyLog(requestid, "SUCCESS:" + result);
				// 计算用户角色
				calculateUserRole(orderSn);
				return "SUCCESS";
			} else {
				logger.error(result);
				logger.error("yeePayCallBack fail");
				orderForXZNotifyLog(requestid, "返回值code非1FAIL:" + result);
				return "FAIL";
			}
		} catch (Exception e) {
			logger.error("yeePayCallBack FAIL:{}-{}" + e.getMessage(), getData, e);
			StringBuffer sb = new StringBuffer();
			sb.append(result);
			sb.append("--->失败原因：");
			sb.append(e.getMessage());
			orderForXZNotifyLog(requestid, "RUNTIME-FAIL:" + (sb.toString().length() >= 6000 ? sb.toString().substring(0, 6000) : sb.toString()));
			return "FAIL";
		}
	}

//	@RequestMapping(value = "/order_queue", method = RequestMethod.POST)
//	@ResponseBody
//	public ResponseEntity<?> order_queue(@RequestBody ResponseUser req) {
		//		Map<String, Object> ret = new HashMap<String, Object>();
		//		try {
		//			int canOrder = 0;
		//			String _str_count = redisUtil.get(RedisKeys.O_ADD_COUNT);
		//			if (!StringUtils.isBlank(_str_count)) {
		//				int currentOrderCount = Integer.parseInt(_str_count);
		//				BaseRestrictions res = baseRestrictionsService.getBaseRestrictionsForCache("O_ADD_MAX_COUNT");
		//				if (res != null && res.getExperience() > 0) {
		//					if (currentOrderCount < res.getExperience()) {//
		//						canOrder = 1;
		//					} else {
		//						canOrder = 0;
		//					}
		//				}
		//			} else {
		//				canOrder = 1;
		//			}
		//			ret.put("canOrder", canOrder);
		//		} catch (Exception e) {
		//			ret.put("canOrder", 0);
		//			logger.error("查询REDIS失败, {}, {}", e.getMessage(), e);
		//		}
//		Map<String, Object> ret = getOrderService2().canOrder(req.getUserId());
//		return new ResponseEntity<>(new ResponseResultModel<Map<String, Object>>(ret), HttpStatus.OK);
//	}

	@SuppressWarnings("unused")
	@RequestMapping(value = "/upload_order", method = RequestMethod.POST, consumes = "application/json")
	@ResponseBody
	public ResponseEntity<?> upload_order(@RequestBody RequestOrderDetail reqOrderDetail, HttpServletRequest request) {
		try {
			reqOrderDetail.initHeader(request);
			/*判断是否可以下单 bein*/
			Map<String, Object> ret = null;
			try {
				ret = getOrderService2().canOrder(reqOrderDetail);
			} catch (Exception e) {
				logger.error("校验iOS是否可支付异常{}", e.getMessage());
			}
			if (MapUtils.getIntValue(ret, "canOrder", 0) == 0) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000, "亲,抢购太火爆请稍后再试..."), HttpStatus.OK);
			}
			if (MapUtils.getIntValue(ret, "canOverSea", 1) == 0) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20429), HttpStatus.OK);
			}
			/*判断是否可以下单   end*/
		
			int check_order_limit_time = 1; //默认客户端2秒轮循一次订单
			//校验商品明细，支付方式、配送类型不能为空
			if (reqOrderDetail == null) {
				logger.error("用户[{}]下单商品明细参数体为空", reqOrderDetail.getUserId());
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if (CollectionUtils.isEmpty(reqOrderDetail.getOrderDetailList())) {
				logger.error("用户[{}]下单商品明细为空", reqOrderDetail.getUserId());
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			// 发货地址不能为空
			UserAddress Address = userAddressService.selectUserAddressById(reqOrderDetail.getUserId(), reqOrderDetail.getMemberDeliveryAddressId());
			if (Address == null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20129), HttpStatus.OK);
			}
			String _ret = sendProductAddressFilter(reqOrderDetail);
			if (StringUtils.isNotBlank(_ret)) {
				return new ResponseEntity<>(new ResponseBaseModel(21885, _ret), HttpStatus.OK);
			}
			BaseRestrictions _close_order_switch = baseRestrictionsService.getBaseRestrictionsForCache("close_order_switch");
			if(_close_order_switch != null && StringUtils.isNotBlank(_close_order_switch.getName())) {
				return new ResponseEntity<>(new ResponseBaseModel(21885, _close_order_switch.getName()), HttpStatus.OK);
			}
			//读取当前果提订单的方式, 1 队列轮循  2 直接提交 默认：1
			int order_upload_type = 1;
			BaseRestrictions _order_upload_type = baseRestrictionsService.getBaseRestrictionsForCache(BaseRestrictionsEnum.ORDER_UPLOAD_TYPE);
			if (_order_upload_type != null && _order_upload_type.getExperience() > 0) {
				order_upload_type = _order_upload_type.getExperience();
			}
			//海外购直接走 直接提交
			for(OrderDetail detail:reqOrderDetail.getOrderDetailList()) {
				GoodsExtends goodsExtends = goodsExtendedAttributeMapper.selectExtendsAttrByGoodsID(detail.getGoodId());
				if (goodsExtends != null && goodsExtends.getOverseasGoods() == 1) {// 有海外购商品
					order_upload_type=2;
					break;
				}
			}
			if (order_upload_type == 1) {
				if (reqOrderDetail.getBalanceAmount() > 0) {
					ResponseResultModel<RespAddOrderInfo> _resp = new ResponseResultModel<RespAddOrderInfo>(new RespAddOrderInfo());
					UserPayInfo payInfo = userPayInfoService.queryByUserId(reqOrderDetail.getUserId());
					if (StringUtils.isBlank(reqOrderDetail.getPayPwd())) {
						_resp.getData().setPayable(false);
						_resp.getData().setPwdAvail(false);
						_resp.getData().setOrderUploadType(2);
						return new ResponseEntity<>(_resp, HttpStatus.OK);
					}
					if (payInfo == null) {//无支付密码
						_resp.getData().setPwdAvail(false);
						_resp.getData().setOrderUploadType(2);
						return new ResponseEntity<>(_resp, HttpStatus.OK);
					}
					if (((int) payInfo.getStatus() != 1)) {
						//支付密码不可用
						_resp.getData().setPwdAvail(false);
						_resp.getData().setOrderUploadType(2);
						return new ResponseEntity<>(_resp, HttpStatus.OK);
					}
					if (StringUtils.isBlank(payInfo.getPwd())) {
						//支付密码为空
						_resp.getData().setPwdAvail(false);
						_resp.getData().setOrderUploadType(2);
						return new ResponseEntity<>(_resp, HttpStatus.OK);
					}
					//密码错误
					if (!StringUtils.equals(reqOrderDetail.getPayPwd(), payInfo.getPwd())) {
						_resp.getData().setPwdAvail(false);
						_resp.getData().setOrderUploadType(2);
						logger.error("支付密码错误返回5:{},{}, {}", reqOrderDetail.getPayPwd(), payInfo.getPwd(), JSONObject.toJSONString(_resp));
						return new ResponseEntity<>(_resp, HttpStatus.OK);
					}
				}
				//地址//发票//
				//				if() {
				//					
				//				}
				//				if() {
				//					
				//				}
				//判断当前队列长度
				long maxQueuesLengs = 700;
				BaseRestrictions queusLengths = baseRestrictionsService.getBaseRestrictionsForCache("O_ADD_MAX_COUNT");
				if (queusLengths != null && queusLengths.getExperience() > 0) {
					maxQueuesLengs = queusLengths.getExperience();
				}
				if (redisUtil.scard(RedisKeys.ORDER_QUEUES_ADD) > maxQueuesLengs) {
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C22208), HttpStatus.OK);
				}

				//logger.error("提交原始数据: 订单号:{} ,    源数据:      {} ", reqOrderDetail.getOrderSn() == null ? "空" : reqOrderDetail.getOrderSn(), JSONObject.toJSONString(reqOrderDetail));
				//if (!orderTokenService.isTokenValid(reqOrderDetail.getToken())) {
				if (!StringUtils.isBlank(reqOrderDetail.getOrderSn())) {//订单上来的订单包含订单号，说明是第二次提交

					//若重复提交,若还在队列中, 在直接用原订单号进行轮循,若处理完成，直接返回支付信息:  
					//判断标准order:amqp:add这个队列中有订单，说明写入队列了， RedisKeys.O_AMQP_ADD_RESULT 这个里面若也有结果，表示该订单处理完成。如果这里没有有，表示在队列中。
					//若order:amqp:add 这个缓存中直接没有结果，则说明是新订单，走写入队列流程
					//RedisKeys.ORDER_QUEUES_ADD
					ResponseResultModel<RespAddOrderInfo> _resp;
					if (redisUtil.sismember(RedisKeys.ORDER_QUEUES_ADD, reqOrderDetail.getOrderSn())) {//在队列中
						//继续轮循
						PollingConfig pollingConfig = new PollingConfig();
						pollingConfig.setOrderUploadStatus(CommonConstants.ORDER_QUEUES_STATUS_NODEAL);
						_resp = new ResponseResultModel<RespAddOrderInfo>(new RespAddOrderInfo());
						_resp.getData().setPollingConfig(pollingConfig);
						_resp.getData().setOrderSn(reqOrderDetail.getOrderSn());
						_resp.getData().setOrderUploadType(order_upload_type);
						return new ResponseEntity<>(_resp, HttpStatus.OK);
					} else {
						//获取订单处理结果,如果无结果，说明还在队列中,如果有结果,说明订单处理完，提示到个人中心去支付
						String order_queues_result_redis_Key = RedisKeys.ORDER_AMQP_ADD_RESULT + reqOrderDetail.getOrderSn();
						String order_query_result = redisUtil.get(order_queues_result_redis_Key);
						if (StringUtils.isBlank(order_query_result)) { //处理结果中没有该订单,说明订单排队中 ,返回继续排队

							return new ResponseEntity<>(null, HttpStatus.OK);
						} else {//已经处理完成
							PollingConfig pollingConfig = new PollingConfig();
							pollingConfig.setOrderUploadStatus(CommonConstants.ORDER_QUEUES_STATUS_DEAL);
							_resp = buildResponseResultModel(order_query_result, reqOrderDetail.getReqHeader(), pollingConfig, reqOrderDetail.getUserId());
							_resp.getData().setOrderSn(reqOrderDetail.getOrderSn());
							_resp.getData().setOrderUploadType(order_upload_type);
							return new ResponseEntity<>(_resp, HttpStatus.OK);
						}
					}
				} else {//订单号为空直接入队
					return new ResponseEntity<>(saveOrder(reqOrderDetail), HttpStatus.OK);
				}

				//写入队列

			} else {
				//				if (!orderTokenService.isTokenValid(reqOrderDetail.getToken())) {
				//					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20001), HttpStatus.OK);
				//				}
				//按照之前原有方式，同步提交订单获取结果
				final RequestOrderDetail _reqOrderDetail = reqOrderDetail;
				//海外购信息单独判断 begin
				final ResponseResultModel<RespAddOrderInfo> addOrderInfo = getOrderService5().overseaGoodsInfo(getOrderService5().addOrderInfo(reqOrderDetail),reqOrderDetail);
				//海外购信息单独判断 end
				if (addOrderInfo.getData().isClearCart()) {
					//清除购物车
					executorService.submit(new Runnable() {
						@Override
						public void run() {
							shoppingCartService.updateRemoveShoppingCart(userService.selectUserRoleById(_reqOrderDetail.getUserId()), addOrderInfo.getData().getpId());
						}
					});
				}
				addOrderInfo.getData().setOrderUploadType(order_upload_type);//老的订单同步处理方式
				return new ResponseEntity<>(addOrderInfo, HttpStatus.OK);
			}
		} catch (Exception e) {
			logger.error("提交订单入队失败 {}", e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	public String sendProductAddressFilter(RequestOrderDetail reqOrderDetail) throws Exception {
		String ret = "";
		if(reqOrderDetail == null) {
			return ret;
		}
		
		Integer _user_adr_id = reqOrderDetail.getMemberDeliveryAddressId();
		if(_user_adr_id == null || _user_adr_id <= 0) {
			return ret;
		}
		
		
		List<OrderDetail> _orderDetail = reqOrderDetail.getOrderDetailList();
		for(OrderDetail odt : _orderDetail) {
			Long _goods_id = odt.getGoodId();
//			String key = "p:nosend:adr:" + _goods_id;
			UserAddress _userAddress = userAddressService.selectUserAddressById(reqOrderDetail.getUserId() , reqOrderDetail.getMemberDeliveryAddressId());
			String _province = _userAddress.getProvince();
//			if(redisUtil.sismember(key, _province)) {				
//				ret = ret + "商品 " + odt.getGoodName() + " 不能发往" + _province + " 省 ,请单独下单!";
//				return ret;
//			}
			
			if(goodsNosendRegionService.exist(_goods_id, _province, 1)) {
				ret = ret + "商品 " + odt.getGoodName() + " 不能发往" + _province + " 省 ,请单独下单!";
//				return ret;
			}
		}
//		if(StringUtils.isNoneBlank(ret)) {
//			ret = ret + "  请重新下单!";
//		}
		return ret;
	}

	//封装支付信息，同时将REDIS缓存中的订单处理结果封装返回
	public ResponseResultModel<RespAddOrderInfo> buildResponseResultModel(String order_result, ReqHeaderVo reqHeader, PollingConfig pollingConfig, Long _login_user_id) throws Exception {
		ResponseResultModel<RespAddOrderInfo> resp = new ResponseResultModel<RespAddOrderInfo>(new RespAddOrderInfo());
		ResponseUser _payUser = userService.selectUserRoleById(_login_user_id);
		JSONObject _json = JSONObject.parseObject(order_result);
		boolean _canPay = false;
		boolean openStoreOrder = false;
		if (!StringUtils.isBlank(_json.getString("data"))) {
			//Gson gson = new Gson();
			//RespAddOrderInfo respOrder = gson.fromJson(_json.getString("data"), RespAddOrderInfo.class);
			RespAddOrderInfo respOrder = GsonUtil.GsonToBean(_json.getString("data"), RespAddOrderInfo.class);
			_canPay = respOrder.isPayable();
			openStoreOrder = respOrder.isOpenStoreOrder();
			resp.setData(respOrder);
		}
		if (_json.getInteger("code") != null && _json.getInteger("code") > 0) {
			resp.setCode(_json.getInteger("code"));
			resp.setMessage(_json.getString("message"));
		}
		//封装轮循参数

		if (pollingConfig != null) {
			BaseRestrictions _res = baseRestrictionsService.getBaseRestrictionsForCache(BaseRestrictionsEnum.CHECK_ORDER_LIMIT_TIME);
			if (_res != null) {
				if (_res.getExperience() > 0) {
					pollingConfig.setOrderQueryLimitTime(_res.getExperience());
				}
			}
			resp.getData().setPollingConfig(pollingConfig);
		}
		//		//封装支付信息
		//		if (reqHeader != null && resp != null) {
		//			//当payable为TRUE时，说明该订单可以支付 ,这个时候才去取支付配置信息
		//			if (_canPay) {
		//				List<PayTypeConfig> _payList = orderObjectService.queryOrderPayType(openStoreOrder, reqHeader, _payUser);
		//				resp.getData().setPayTypeConfigList(_payList);
		//			}
		//		}
		return resp;
	}

	public ResponseResultModel<RespAddOrderInfo> saveOrder(RequestOrderDetail reqOrderDetail) throws Exception {
		PollingConfig pollingConfig = new PollingConfig();
		pollingConfig.setOrderUploadStatus(CommonConstants.ORDER_QUEUES_STATUS_NODEAL);
		ResponseResultModel<RespAddOrderInfo> resp = new ResponseResultModel<RespAddOrderInfo>(new RespAddOrderInfo());
		StringBuffer orderSn = new StringBuffer();
		orderSn.append(CommonConstants.ORDER_OBJECT_PREFIX).append(OrderUtil.getOrderSn());
		BaseRestrictions _res = baseRestrictionsService.getBaseRestrictionsForCache(BaseRestrictionsEnum.CHECK_ORDER_LIMIT_TIME);
		if (_res != null) {
			if (_res.getExperience() > 0) {
				pollingConfig.setOrderQueryLimitTime(_res.getExperience());
			}
		}
		reqOrderDetail.setOrderSn(orderSn.toString());
		reqOrderDetail.setParentOrderSn(orderSn.toString());
		orderQueueService.createOrder(reqOrderDetail);
		//写入REDIS
		//logger.error("写入队列成功, 队列数据 : {} ", JSONObject.toJSONString(reqOrderDetail).toString());
		redisUtil.sadd(RedisKeys.ORDER_QUEUES_ADD, reqOrderDetail.getOrderSn());
		resp.getData().setOrderSn(orderSn.toString());
		resp.getData().setPollingConfig(pollingConfig);
		resp.getData().setOrderUploadType(1);//轮循处理订单类型
		resp.getData().setPayable(true);
		resp.getData().setPwdAvail(true);

		return resp;
	}

	@RequestMapping(value = "/check_order", method = RequestMethod.POST, consumes = "application/json")
	@ResponseBody
	public ResponseEntity<?> check_order(@RequestBody RequestOrderDetail reqOrderDetail, HttpServletRequest request) {
		try {
			reqOrderDetail.initHeader(request);
			if (StringUtils.isBlank(reqOrderDetail.getOrderSn())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if (reqOrderDetail.getUserId() == null || reqOrderDetail.getUserId() <= 0) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			//检查订单是否落地,和订单状态 : 先查询订单处理结果缓存
			String order_queues_result_redis_Key = RedisKeys.ORDER_AMQP_ADD_RESULT + reqOrderDetail.getOrderSn();
			String order_query_result = redisUtil.get(order_queues_result_redis_Key);
			if (StringUtils.isBlank(order_query_result)) { //说明订单排队中 
				ResponseResultModel<RespAddOrderInfo> resp = new ResponseResultModel<RespAddOrderInfo>(new RespAddOrderInfo());
				PollingConfig pollingConfig = new PollingConfig();
				pollingConfig.setOrderUploadStatus(CommonConstants.ORDER_QUEUES_STATUS_NODEAL);
				resp.setData(new RespAddOrderInfo());
				resp.getData().setPollingConfig(pollingConfig);
				resp.getData().setOrderSn(reqOrderDetail.getOrderSn());
				resp.getData().setOrderUploadType(1);//订单处理方式,1 轮循
				resp.setCode(10000);
				resp.setMessage("成功");
				return new ResponseEntity<>(resp, HttpStatus.OK);
			}
			//订单处理完成，有处理结果
			PollingConfig pollingConfig = new PollingConfig();
			pollingConfig.setOrderUploadStatus(CommonConstants.ORDER_QUEUES_STATUS_DEAL);
			ResponseResultModel<RespAddOrderInfo> _resp = buildResponseResultModel(order_query_result, reqOrderDetail.getReqHeader(), pollingConfig, reqOrderDetail.getUserId());
			if (_resp.getCode() != 10000) {
				_resp.getData().getPollingConfig().setErrorType(3L);
				_resp.getData().setPayable(false);
				_resp.setCode(10000);
				_resp.setMessage("成功");
			} else {
				boolean isErrorGoods = false; //是否存在库存不足商品
				List<ErrorMsgGoods> _errorGoodsList = _resp.getData().getErrorMsg().getInvalidGoods();
				for (ErrorMsgGoods errGoods : _errorGoodsList) {
					if (errGoods.getQuantity() < 1) {
						isErrorGoods = true;
						break;
					}
				}
				if (isErrorGoods) {//存在库存不足商品
					_resp.getData().getPollingConfig().setErrorType(2L);
					_resp.getData().setPayable(false);
				} else {
					//有异常失效产品   或者有价格变动
					if (CollectionUtils.isNotEmpty(_errorGoodsList) || _resp.getData().getErrorMsg().isHasPriceChanger()) {
						_resp.getData().getPollingConfig().setErrorType(3L);
						_resp.getData().setPayable(false);
					} else {
						_resp.getData().getPollingConfig().setErrorType(1L);
						_resp.getData().setPayable(true);
					}
				}
			}

			_resp.getData().setOrderSn(reqOrderDetail.getOrderSn());
			_resp.getData().setOrderUploadType(1);
			//logger.error("订单轮循结果: {}----REDIS KEY :    {}------ {}", reqOrderDetail.getOrderSn(), JSONObject.toJSONString(_resp), order_query_result);
			return new ResponseEntity<>(_resp, HttpStatus.OK);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("订单 {} 轮循失败, {}, {}", reqOrderDetail.getOrderSn(), e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	@RequestMapping(value = "/OrderCommisionDetail", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getOrderCommision(@RequestBody RequestOrderDetail reqOrderDetail,HttpServletRequest request) throws Exception {
		if (ParameterUtils.validParams(reqOrderDetail.getOrderDetailIds())) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
		}
		try {
			List<Map<String, Object>> ListMap = getOrderService2().selectOrderObjectCommision(reqOrderDetail.getOrderDetailIds());
			if (!ListUtils.isNotEmpty(ListMap)) {
				return new ResponseEntity<>(new ResponseBaseModel(20000, "数据偷渡到火星了，请联系客服遣返"), HttpStatus.OK);
			}
			return  new ResponseEntity<>(new ResponseResultModel<>(ListMap), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("接口请求失败：{}", e.getMessage());
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
}
